package com.itranswarp.learnjava.dao;

import com.itranswarp.learnjava.bean.Permission;
import com.itranswarp.learnjava.bean.RolePermission;
import com.itranswarp.learnjava.utils.DBUtil;
import com.itranswarp.learnjava.bean.Role;
import com.itranswarp.learnjava.bean.PageResult;

import java.util.ArrayList;

import java.sql.*;
public class PermissionDAO {
    public static PageResult<Permission> getAllPermissions(int offset,int pageSize) throws SQLException {
        Connection conn = DBUtil.getConnection();
        PageResult<Permission> result = new PageResult<>();
        ArrayList<Permission> permissions = new ArrayList<>();
        String sql = "SELECT id, name, code, `type`, created_at FROM permissions limit ?, ?;";
        try(PreparedStatement stmt = conn.prepareStatement(sql);){
            stmt.setInt(1, offset *pageSize);
            stmt.setInt(2, pageSize);
            ResultSet rs = stmt.executeQuery();
            while (rs.next()) {
                permissions.add(extractPermissionRow(rs));
            }
            rs.close();
            stmt.close();
            result.pageSize = pageSize;
            result.currentPage = offset + 1;
            result.records = permissions;
            result.totalRecords = getPermissionCount();
            result.totalPages = (int) Math.ceil((double) result.totalRecords / pageSize);

        }
        return result;
    }

    public static ArrayList<Permission>getPermissionsById(int id) {
        ArrayList<Permission> permissions = new ArrayList<>();
        Connection conn = DBUtil.getConnection();
        String sql = "SELECT DISTINCT p.id, p.name, p.code FROM users u\n" +
                "join user_role ur ON u.id = ur.user_id\n" +
                "JOIN role_permissions rp ON ur.role_id = rp.role_id\n" +
                "JOIN permissions p ON rp.permission_id = p.id\n" +
                "WHERE u.id = ?;\n";
        try(PreparedStatement stmt = conn.prepareStatement(sql)){
            stmt.setInt(1, id);
            ResultSet rs = stmt.executeQuery();
            while (rs.next()) {
                permissions.add(extractPermissionRow(rs));
            }
            return permissions;
        } catch (SQLException e) {
            return permissions;
        }

    }

    public static PageResult<RolePermission> getPermisionsByRoleId(int roleId, int offset,int pageSize) {
        ArrayList<RolePermission> permissions = new ArrayList<>();
        PageResult<RolePermission> result = new PageResult<>();

        try {
            Connection conn = DBUtil.getConnection();
            String sql = "select rp.created_at AS created_at,rp.id AS user_role_id,r.role_name AS role_name,p.code AS permission_code,p.name AS permission_name FROM roles r JOIN role_permissions rp ON r.id = rp.role_id JOIN permissions p ON rp.permission_id = p.id WHERE r.id = ? ORDER BY p.id LIMIT ?, ?";
            PreparedStatement stmt = conn.prepareStatement(sql);
            stmt.setInt(1, roleId);
            stmt.setInt(2, offset *pageSize);
            stmt.setInt(3, pageSize);
            ResultSet rs = stmt.executeQuery();
            while (rs.next()) {
                permissions.add(extractRow(rs));
            }
            rs.close();
            stmt.close();

            result.pageSize = pageSize;
            result.currentPage = offset + 1;
            result.records = permissions;
            result.totalRecords = getRoelPermissionCount(roleId);
            result.totalPages = (int) Math.ceil((double) result.totalRecords / pageSize);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
    static RolePermission extractRow(ResultSet rs) throws SQLException {
        var role = new RolePermission(rs.getInt("user_role_id"), rs.getString("permission_name"), rs.getString("permission_code"), rs.getString("created_at"));
        return role;
    }

    static Permission extractPermissionRow(ResultSet rs)throws SQLException{
        var permission = new Permission(rs.getLong("id"), rs.getString("name"), rs.getString("code"));
        return permission;
    }

    static int getPermissionCount() throws SQLException {
        Connection conn = DBUtil.getConnection();
        String sql = "select COUNT(*) FROM permissions";
        int totalRecords = 0;
        try(PreparedStatement stmt = conn.prepareStatement(sql)) {
            ResultSet rs = stmt.executeQuery();
            if(rs.next()){
                totalRecords = rs.getInt(1);
            }
        }
        return totalRecords;
    }

    static int getRoelPermissionCount(int roleId) {
        Connection conn = DBUtil.getConnection();
        String sql = "select COUNT(*) FROM roles r JOIN role_permissions rp ON r.id = rp.role_id JOIN permissions p ON rp.permission_id = p.id WHERE r.id = ? ORDER BY p.id;";
        int totalRecords=0;
        try(PreparedStatement ps = conn.prepareStatement(sql)){
            ps.setInt(1, roleId);
            ResultSet rs = ps.executeQuery(); // ✅ 正确方式
            if(rs.next()){
                totalRecords = rs.getInt(1);
            }
            rs.close();
            ps.close();
            return totalRecords;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

}
